import json

from django.http import HttpResponse
from django.shortcuts import render

import UITestCase.models


# Create your views here.


def get_systems(request):

    if request.method == 'GET':  # 当提交表单时
        ui_systems = UITestCase.models.UISystem.objects.values("id", "system_name")
        return HttpResponse(json.dumps(list(ui_systems)), content_type="application/json")
    else:
        return HttpResponse('方法错误')


def get_models_page(request):
    return render(request, 'models.html')


def get_models(request):

    if request.method == 'POST':  # 当提交表单时
        params = json.loads(request.body)
        if len(params) == 0:
            ui_models = UITestCase.models.UIModel.objects.filter().values("id", "model_name", "system_id")
            models_list = []
            ui_models_list = list(ui_models)
            for ui_model in ui_models_list:
                system_name = UITestCase.models.UISystem.objects.filter(id=ui_model["system_id"]).values("system_name")
                ui_model["system_name"] = system_name[0]["system_name"]
                models_list.append(ui_model)
            return HttpResponse(json.dumps(models_list), content_type="application/json")
        else:
            json_result = json.loads(request.body)
            system_id = json_result.get('systemID')
            ui_models = UITestCase.models.UIModel.objects.filter(system_id=system_id).values("id", "model_name", "system_id")
            models_list = []
            ui_models_list = list(ui_models)
            for ui_model in ui_models_list:
                system_name = UITestCase.models.UISystem.objects.filter(id=ui_model["system_id"]).values("system_name")
                ui_model["system_name"] = system_name[0]["system_name"]
                models_list.append(ui_model)
            return HttpResponse(json.dumps(models_list), content_type="application/json")
    else:
        return HttpResponse('方法错误')


def get_model_add_page(request):
    return render(request, 'model_add.html')


def add_model(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.body != "{}":
            params = json.loads(request.body)
            model_name = params.get('modelName')
            system_id = params.get('systemID')
            UITestCase.models.UIModel.objects.create(
                model_name=model_name,
                system_id=system_id,
                create_by="Tester",
                create_time=UITestCase.models.timezone.now(),
                update_time=UITestCase.models.timezone.now()
            )

            return HttpResponse(json.dumps("Add model Success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


def delete_model(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.body != "{}":
            params = json.loads(request.body)
            model_id = params.get('cell')[4:]
            UITestCase.models.UIModel.objects.filter(id=model_id).delete()

            return HttpResponse(json.dumps("Delete model success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


def get_pages_page(request):
    return render(request, 'pages.html')


def get_pages(request):
    if request.method == 'POST':  # 当提交表单时
        params = json.loads(request.body)
        if len(params) == 0:
            ui_pages = UITestCase.models.UIPage.objects.values("id", "page_name", "page_path", "model_id", "system_id")
            pages_list = []
            ui_pages_list = list(ui_pages)
            for ui_page in ui_pages_list:
                system_name = UITestCase.models.UISystem.objects.filter(id=ui_page["system_id"]).values("system_name")
                model_name = UITestCase.models.UIModel.objects.filter(id=ui_page["model_id"]).values("model_name")
                ui_page["system_name"] = system_name[0]["system_name"]
                ui_page["model_name"] = model_name[0]["model_name"]
                pages_list.append(ui_page)
            return HttpResponse(json.dumps(list(ui_pages)), content_type="application/json")
        else:
            json_result = json.loads(request.body)
            model_id = json_result.get('modelID')
            ui_pages = UITestCase.models.UIPage.objects.filter(model_id=model_id).values("id", "page_name", "page_path", "model_id", "system_id")
            return HttpResponse(json.dumps(list(ui_pages)), content_type="application/json")
    else:
        return HttpResponse('方法错误')


def get_page_add_page(request):
    return render(request, 'page_add.html')


def add_page(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.body != "{}":
            params = json.loads(request.body)

            system_id = params.get('systemID')
            model_id = params.get('modelID')
            page_name = params.get('pageName')
            page_path = params.get('pagePath')

            UITestCase.models.UIPage.objects.create(
                page_name=page_name,
                page_path=page_path,
                model_id=model_id,
                system_id=system_id,
                create_by="Tester",
                create_time=UITestCase.models.timezone.now(),
                update_time=UITestCase.models.timezone.now()
            )
            return HttpResponse(json.dumps("Add page Success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


def delete_page(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.body != "{}":
            params = json.loads(request.body)
            page_id = params.get('cell')[4:]
            UITestCase.models.UIPage.objects.filter(id=page_id).delete()

            return HttpResponse(json.dumps("Delete page success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


def get_elements_page(request):
    return render(request, 'elements.html')


def get_elements_add_page(request):
    return render(request, 'element_add.html')


def get_elements(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        params = json.loads(request.body)
        if len(params) > 0:
            json_result = json.loads(request.body)
            page_id = json_result.get('pageId')
            ui_elements = UITestCase.models.UIElement.objects.filter(page_id=page_id).values("id", "element_name")

            return HttpResponse(json.dumps(list(ui_elements)), content_type="application/json")
        else:
            ui_elements = UITestCase.models.UIElement.objects.values("id", "element_name", "page_id", "find_type", "find_param", "another_find_type", "another_find_param")

            elements_list = []
            ui_elements_list = list(ui_elements)
            for ui_element in ui_elements_list:
                page_data = UITestCase.models.UIPage.objects.filter(id=ui_element["page_id"]).values("id", "page_name", "model_id", "system_id")
                page_data_list = list(page_data)
                system_name = UITestCase.models.UISystem.objects.filter(id=page_data_list[0]["system_id"]).values("system_name")
                model_name = UITestCase.models.UIModel.objects.filter(id=page_data_list[0]["model_id"]).values("model_name")
                ui_element["system_name"] = system_name[0]["system_name"]
                ui_element["model_name"] = model_name[0]["model_name"]
                ui_element["page_name"] = page_data[0]["page_name"]
                if ui_element["find_type"] == "1":
                    ui_element["find_type"] = "id"
                elif ui_element["find_type"] == "2":
                    ui_element["find_type"] = "xPath"
                elif ui_element["find_type"] == "3":
                    ui_element["find_type"] = "CSS Selector"

                if ui_element["another_find_type"] == "1":
                    ui_element["another_find_type"] = "id"
                elif ui_element["another_find_type"] == "2":
                    ui_element["another_find_type"] = "xPath"
                elif ui_element["another_find_type"] == "3":
                    ui_element["another_find_type"] = "CSS Selector"

                elements_list.append(ui_element)

            return HttpResponse(json.dumps(list(elements_list)), content_type="application/json")
    else:
        return HttpResponse('方法错误')


def add_element(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.body != "{}":
            params = json.loads(request.body)

            page_id = params.get('pageID')
            element_name = params.get('elementName')
            find_type = params.get('findFunc')
            find_param = params.get('findParams')
            another_find_type = params.get('anotherFindFunc')
            another_find_param = params.get('anotherFindParams')

            UITestCase.models.UIElement.objects.create(
                page_id=page_id,
                element_name=element_name,
                find_type=find_type,
                find_param=find_param,
                another_find_type=another_find_type,
                another_find_param=another_find_param,
                create_by="Tester",
                create_time=UITestCase.models.timezone.now(),
                update_time=UITestCase.models.timezone.now()
            )
            return HttpResponse(json.dumps("Add element Success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


def delete_element(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.body != "{}":
            params = json.loads(request.body)
            element_id = params.get('cell')[4:]
            UITestCase.models.UIElement.objects.filter(id=element_id).delete()

            return HttpResponse(json.dumps("Delete element success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


#  业务模块
def get_scenarios_page(request):
    return render(request, 'business_scenarios.html')


def get_scenarios_add_page(request):
    return render(request, 'business_scenarios_add.html')


def get_scenarios_element_page(request):
    return render(request, "business_scenarios_element.html")


def get_scenarios_element_add_page(request):
    return render(request, 'business_scenarios_element_add.html')


def get_scenarios(request):
    if request.method in ("POST"):  # 当提交表单时
        # 判断是否传参
        params = json.loads(request.body)
        if len(params) > 0:
            json_result = json.loads(request.body)
            system_id = json_result.get('systemID')
            ui_scenarios = UITestCase.models.UIScenarios.objects.filter(system_id=system_id).values("id", "element_name")

            return HttpResponse(json.dumps(list(ui_scenarios)), content_type="application/json")
        else:
            ui_scenarios = UITestCase.models.UIScenarios.objects.values("id", "scenarios_name", "system_id")
            ui_scenarios_data_list = []
            ui_scenarios_list = list(ui_scenarios)
            for ui_scenarios_data in ui_scenarios_list:
                system_id = ui_scenarios_data["system_id"]
                system_name = UITestCase.models.UISystem.objects.filter(id=system_id).values("system_name")
                ui_scenarios_data["system_name"] = system_name[0]["system_name"]
                ui_scenarios_data_list.append(ui_scenarios_data)
            return HttpResponse(json.dumps(list(ui_scenarios)), content_type="application/json")
    else:
        return HttpResponse('方法错误')


def add_scenarios(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        params = json.loads(request.body)
        if len(params) > 0:
            params = json.loads(request.body)

            scenarios_name = params.get('scenariosName')
            system_id = params.get('systemID')

            UITestCase.models.UIScenarios.objects.create(
                scenarios_name=scenarios_name,
                system_id=system_id,
                create_by="Tester",
                create_time=UITestCase.models.timezone.now(),
                update_time=UITestCase.models.timezone.now()
            )
            return HttpResponse(json.dumps("Add scenarios Success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


def delete_scenarios(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.body != "{}":
            params = json.loads(request.body)
            scenarios_id = params.get('cell')[4:]
            UITestCase.models.UIScenarios.objects.filter(id=scenarios_id).delete()

            return HttpResponse(json.dumps("Delete element success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


def get_scenarios_element(request):
    if request.method == 'POST':  # 当提交表单时
        params = json.loads(request.body)
        if len(params) == 0:
            ui_scenarios_elements = UITestCase.models.UIScenariosElements.objects.values("id", "scenarios_id", "system_id", "model_id", "page_id", "element_id", "sort_id").order_by("sort_id")
            scenarios_elements_list = []
            ui_scenarios_elements_list = list(ui_scenarios_elements)
            for ui_scenarios_element in ui_scenarios_elements_list:
                if ui_scenarios_element["system_id"] == "":
                    if ui_scenarios_element["operate"] == "get_url":
                        print()
                    elif ui_scenarios_element["operate"] == "Insert_Scenarios":
                        ui_scenarios_element["scenarios_name"] = UITestCase.models.UIScenarios.objects.filter(id=ui_scenarios_element["params"]).values_list("scenarios_name")[0][0]
                        scenarios_elements_list.append(ui_scenarios_element)
                else:
                    system_name = UITestCase.models.UISystem.objects.filter(id=ui_scenarios_element["system_id"]).values("system_name")
                    scenarios_name = UITestCase.models.UIScenarios.objects.filter(id=ui_scenarios_element["scenarios_id"]).values("scenarios_name")
                    model_name = UITestCase.models.UIScenarios.objects.filter(id=ui_scenarios_element["model_id"]).values("model_name")
                    page_name = UITestCase.models.UIScenarios.objects.filter(id=ui_scenarios_element["page_id"]).values("page_name")
                    element_name = UITestCase.models.UIScenarios.objects.filter(id=ui_scenarios_element["element_id"]).values("element_name")
                    ui_scenarios_element["system_name"] = system_name[0]["system_name"]
                    ui_scenarios_element["scenarios_name"] = scenarios_name[0]["scenarios_name"]
                    ui_scenarios_element["model_name"] = model_name[0]["model_name"]
                    ui_scenarios_element["page_name"] = page_name[0]["page_name"]
                    ui_scenarios_element["element_name"] = element_name[0]["element_name"]
                    scenarios_elements_list.append(ui_scenarios_element)
            return HttpResponse(json.dumps(list(scenarios_elements_list)), content_type="application/json")
        else:
            scenarios_id = json.loads(request.body).get("scenariosID")
            ui_scenarios_elements = UITestCase.models.UIScenariosElements.objects.filter(scenarios_id=scenarios_id).values("id", "scenarios_id", "system_id", "model_id", "page_id", "element_id", "operator", "params", "sort_id").order_by("sort_id")
            final_scenarios_elements_list = []
            ui_scenarios_elements_list = list(ui_scenarios_elements)
            for ui_scenarios_element in ui_scenarios_elements_list:
                if ui_scenarios_element["system_id"] == "":
                    if ui_scenarios_element["operator"] == "get_url":
                        ui_scenarios_element["system_id"] = None
                        ui_scenarios_element["model_id"] = None
                        ui_scenarios_element["page_id"] = None
                        ui_scenarios_element["element_id"] = None
                    elif ui_scenarios_element["operator"] == "Insert_Scenarios":
                        ui_scenarios_element["scenarios_name"] = UITestCase.models.UIScenarios.objects.filter(id=ui_scenarios_element["params"]).values("scenarios_name")[0]["scenarios_name"]
                        ui_scenarios_element["system_id"] = None
                        ui_scenarios_element["model_id"] = None
                        ui_scenarios_element["page_id"] = None
                        ui_scenarios_element["element_id"] = None
                else:
                    system_name = UITestCase.models.UISystem.objects.filter(id=ui_scenarios_element["system_id"]).values("system_name")
                    scenarios_name = UITestCase.models.UIScenarios.objects.filter(id=ui_scenarios_element["scenarios_id"]).values("scenarios_name")
                    model_name = UITestCase.models.UIModel.objects.filter(id=ui_scenarios_element["model_id"]).values("model_name")
                    page_name = UITestCase.models.UIPage.objects.filter(id=ui_scenarios_element["page_id"]).values("page_name")
                    if ui_scenarios_element["element_id"] == "":
                        ui_scenarios_element["element_name"] = ""
                    else:
                        element_name = UITestCase.models.UIElement.objects.filter(id=ui_scenarios_element["element_id"]).values("element_name")
                        ui_scenarios_element["element_name"] = element_name[0]["element_name"]
                    ui_scenarios_element["system_name"] = system_name[0]["system_name"]
                    ui_scenarios_element["scenarios_name"] = scenarios_name[0]["scenarios_name"]
                    ui_scenarios_element["model_name"] = model_name[0]["model_name"]
                    ui_scenarios_element["page_name"] = page_name[0]["page_name"]

                final_scenarios_elements_list.append(ui_scenarios_element)
            json_response = json.dumps(final_scenarios_elements_list)
            return HttpResponse(json_response, content_type="application/json")
    else:
        return HttpResponse('方法错误')


def add_scenarios_element(request):
    global sort_id
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        params = json.loads(request.body)
        if len(params) > 0:
            params = json.loads(request.body)
            operate = params.get("operateFunc")
            operate_type = params.get("operateType")
            if operate == "input":
                scenarios_id = params.get("scenariosId")
                system_id = params.get('systemId')
                model_id = params.get('modelId')
                page_id = params.get('pageId')
                element_id = params.get('elementId')
                param = params.get("operateParams")
            elif operate == "get_url":
                scenarios_id = params.get("scenariosId")
                system_id = ""
                model_id = ""
                page_id = ""
                element_id = ""
                param = params.get("operateParams")
            else:
                scenarios_id = params.get("scenariosId")
                system_id = params.get('systemId')
                model_id = params.get('modelId')
                page_id = params.get('pageId')
                element_id = params.get('elementId')
                param = ""

            if operate_type == "insert":
                insert_after_sort_id = params.get("insertAfterSortId")
                sort_id = int(insert_after_sort_id) + 1
                need_change_id = UITestCase.models.UIScenariosElements.objects.filter(scenarios_id=scenarios_id, sort_id__gte=sort_id).values_list("sort_id")
                for wanted_id in need_change_id:
                    obj = UITestCase.models.UIScenariosElements.objects.filter(scenarios_id=scenarios_id, sort_id=wanted_id[0])
                    sorted_id = int(list(obj)[0].sort_id) + 1
                    UITestCase.models.UIScenariosElements.objects.filter(scenarios_id=scenarios_id, sort_id=wanted_id[0]).update(sort_id=sorted_id)
            elif operate_type == "add":
                sort_id_list = UITestCase.models.UIScenariosElements.objects.filter(scenarios_id=scenarios_id).values_list("sort_id").order_by("-sort_id")
                if len(sort_id_list) > 0:
                    sort_id = int(sort_id_list[0][0]) + 1
                else:
                    sort_id = 1
                if operate == 'Insert_Scenarios':
                    param = params.get("operateParams")

            UITestCase.models.UIScenariosElements.objects.create(
                scenarios_id=scenarios_id,
                system_id=system_id,
                model_id=model_id,
                page_id=page_id,
                element_id=element_id,
                operator=operate,
                params=param,
                sort_id=sort_id,
                create_by="Tester",
                create_time=UITestCase.models.timezone.now(),
                update_time=UITestCase.models.timezone.now()
            )
            return HttpResponse(json.dumps("Add element to scenarios Success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')


def delete_scenarios_element(request):
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        params = json.loads(request.body)
        if len(params) > 0:
            params = json.loads(request.body)
            sort_id_del = params.get('sortId')
            scenarios_id = params.get("scenariosId")

            UITestCase.models.UIScenariosElements.objects.filter(sort_id=sort_id_del).delete()

            need_change_id = UITestCase.models.UIScenariosElements.objects.filter(scenarios_id=scenarios_id, sort_id__gt=sort_id_del).values_list("sort_id")
            for wanted_id in need_change_id:
                obj = UITestCase.models.UIScenariosElements.objects.get(sort_id=wanted_id[0])
                obj.sort_id = int(obj.sort_id) - 1
                obj.save()

            return HttpResponse(json.dumps("Delete page success", ensure_ascii=False), content_type="application/json")
        else:
            return HttpResponse('参数为空')
    else:
        return HttpResponse('方法错误')
